const router = require('koa-router')();

const pool = require('../scripts/mysql');

// 查询书籍列表接口
router.get('/booklist', async ctx => {
  const sql = `SELECT * FROM book`;
  const [results] = await pool.query(sql);
  ctx.body = { code: 0, data: results };
});

// 添加书籍接口
router.post('/addbook', async ctx => {
  const { name, link, publish_house, amount, price } = ctx.request.body;
  const sql = `INSERT INTO book(name,link,publish_house,amount,price) VALUES('${name}','${link}','${publish_house}','${amount}','${price}')`;
  await pool.query(sql);
  ctx.body = { code: 0, msg: '添加书籍成功' };
});

// 更新书籍信息接口
router.post('/updatebook', async ctx => {
  const { id, name, link, publish_house, amount, price } = ctx.request.body;
  let updateStr = '';
  if (name) {
    updateStr += `name='${name}',`;
  }
  if (link) {
    updateStr += `link='${link}',`;
  }
  if (publish_house) {
    updateStr += `publish_house='${publish_house}',`;
  }
  if (amount) {
    updateStr += `amount='${amount}',`;
  }
  if (price) {
    updateStr += `price='${price}',`;
  }
  updateStr = updateStr.slice(0, -1);
  const sql = `UPDATE book SET ${updateStr} WHERE id=${id}`;
  await pool.query(sql);
  ctx.body = { code: 0, msg: '更新成功' };
});

// 删除书籍信息接口
router.post('/deletebook', async ctx => {
  const { id } = ctx.request.body;
  const sql = `DELETE FROM book WHERE id=${id}`;
  await pool.query(sql);
  ctx.body = { code: 0, msg: '删除成功' };
});

// 根据名称和出版社搜索书籍信息
router.get('/searchbook', async ctx => {
  let { name } = ctx.query;
  console.log('name', name);
  let sql = `SELECT * FROM book WHERE name LIKE '%${name}%'`;
  const [results] = await pool.query(sql);
  ctx.body = { code: 0, data: results };
});

module.exports = router;
